package com.seer.seertest.service;

import com.alibaba.fastjson2.JSON;
import com.seer.seertest.entity.SaleOrder;
import com.seer.seertest.entity.SaleOrderLine;
import com.seer.seertest.mapper.SaleOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class OrderService {

    @Value("${order.sign.in.url}")
    private String SIGN_IN_URL;

    @Value("${order.create.inbound.url}")
    private String CREATE_INBOUND_URL;

    @Value("${order.login.username}")
    private String LOGIN_USERNAME;

    @Value("${order.login.password}")
    private String LOGIN_PASSWORD;


    @Autowired
    private SaleOrderMapper saleOrderMapper;

    public void processOrders() {
        try {
            String token = login();
            if (token != null) {
                List<Map<String, Object>> orders = fetchOrders();
                for (Map<String, Object> order : orders) {
                    sendOrder(order, token);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String login() throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(SIGN_IN_URL);

        Map<String, String> loginData = new HashMap<>();
        loginData.put("username", LOGIN_USERNAME);
        loginData.put("password", LOGIN_PASSWORD);
        String json = JSON.toJSONString(loginData);
        StringEntity entity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);
            Map<String, Object> responseMap = JSON.parseObject(responseBody, HashMap.class);
            Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
            if (dataMap != null) {
                // 从 dataMap 中直接提取 token
                return (String) dataMap.get("token");
            } else {
                log.info("未找到 data 字段");
            }
        } else {
            log.info("登录失败: {}", response.getStatusLine().getReasonPhrase());
            return null;
        }
        return null;
    }

    private List<Map<String, Object>> fetchOrders() {
        List<SaleOrder> saleOrders = saleOrderMapper.getAllOrders();
        List<Map<String, Object>> allOrders = new ArrayList<>();
        for (SaleOrder saleOrder : saleOrders) {
            List<SaleOrderLine> orderLines = saleOrderMapper.getOrderLinesByOrderId(saleOrder.getId());
            Map<String, Object> order = new HashMap<>();
            Map<String, Object> orderInfo = new HashMap<>();
            orderInfo.put("state", 0);
            orderInfo.put("remark", saleOrder.getRemark());
            orderInfo.put("template", "料箱入库");
            order.put("order", orderInfo);
            List<Map<String, Object>> lines = new ArrayList<>();
            for (SaleOrderLine line : orderLines) {
                Map<String, Object> lineMap = new HashMap<>();
                lineMap.put("part", line.getMaterial());
                lineMap.put("expectedQty", null);
                lineMap.put("actualQty", line.getQty().doubleValue());
                lineMap.put("lotNo", "");
                lines.add(lineMap);
            }
            order.put("lines", lines);
            allOrders.add(order);
        }
        return allOrders;
    }

    private void sendOrder(Map<String, Object> order, String token) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(CREATE_INBOUND_URL);

        String json = JSON.toJSONString(order);
        StringEntity entity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + token);

        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);
            log.info("订单发送成功: {}", responseBody);
        } else {
            log.info("订单发送失败: {}", response.getStatusLine().getReasonPhrase());
        }
    }

}
